package dapp

import (
	"github.com/spf13/cobra"
	"hundsun.com/hsl/hschain/cmd/cli/common"
	"hundsun.com/hsl/hschain/common/util"
	"hundsun.com/hsl/hschain/protos/ledger"
	protosrpc "hundsun.com/hsl/hschain/protos/rpc"
	service "hundsun.com/hsl/hschain/rpc/impl"
)

const (
	funcName = "txPool"
	cmdDes   = "Tx pool query"
)

//TxPoolCmd ...
func TxPoolCmd() *cobra.Command {
	txCmd := &cobra.Command{
		Use:   funcName,
		Short: cmdDes,
		Long:  cmdDes,
	}
	txCmd.AddCommand(queryTxPoolByHashCmd())
	txCmd.AddCommand(queryTxPoolSizeCmd())
	txCmd.AddCommand(queryTxPoolHashesCmd())
	return txCmd
}

func queryTxPoolByHashCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "queryPendingTx",
		Short: "Query pending tx by hash",
		Long:  "Query pending tx by hash",
		Run:   queryTxPoolByHash,
	}

	cmd.Flags().StringP("hash", "", "", "transaction hash")
	cmd.MarkFlagRequired("hash")

	return cmd
}

func queryTxPoolByHash(cmd *cobra.Command, args []string) {
	hash, _ := cmd.Flags().GetString("hash")
	param := &protosrpc.TxHashParam{
		TxHash: hash,
	}

	rpcLaddr, _ := cmd.Flags().GetString(common.FlagRPCLaddr)
	common.RPCCall(rpcLaddr, service.PeekTxPool, param,
		func(res interface{}) {
			obj := res.(service.JSONRPCResp)
			valI, _ := util.Bytes2Struct(&ledger.Transaction{}, obj.Payload)
			val := valI.(*ledger.Transaction)
			common.PrintJSON(common.FromPbTransaction(val))
		})
}

func queryTxPoolSizeCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "queryTxPoolSize",
		Short: "Query tx pool size",
		Long:  "Query tx pool size",
		Run:   queryTxPoolSize,
	}
	return cmd
}

func queryTxPoolSize(cmd *cobra.Command, args []string) {
	rpcLaddr, _ := cmd.Flags().GetString(common.FlagRPCLaddr)
	common.RPCCall(rpcLaddr, service.TxPoolSize, nil, nil)
}

func queryTxPoolHashesCmd() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "queryPendingHashes",
		Short: "Query tx pool hashes",
		Long:  "Query tx pool hashes",
		Run:   queryTxPoolHashes,
	}

	cmd.Flags().Uint16P("size", "", 10, "query size")
	return cmd
}

func queryTxPoolHashes(cmd *cobra.Command, args []string) {
	size, _ := cmd.Flags().GetUint16("size")
	rpcLaddr, _ := cmd.Flags().GetString(common.FlagRPCLaddr)
	common.RPCCall(rpcLaddr, service.TxPoolHashes, size, func(res interface{}) {
		obj := res.(service.JSONRPCResp)
		valI, _ := util.Bytes2Struct(&protosrpc.Strings{}, obj.Payload)
		val := valI.(*protosrpc.Strings)
		if val.Results == nil {
			val.Results = make([]string, 0)
		}
		common.PrintJSON(val.Results)
	})
}
